using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using JNPF.Basics.Models;
using JNPF.Basics.Logic;
using JNPF.Utils;
using System.Threading.Tasks;
using System.Linq;
using JNPF.Utils.Controller;
using JNPF.Basics.Logic.Common.Login;
using JNPF.Utils.Extensions;

namespace JNPF.Basics.Controller
{
    [Route("api/Jiushi/[Controller]")]
    public class CustomerbaseController : BaseApiController
    {
        private CustomerbaseBll CustomerbaseService = new CustomerbaseBll();
        private BillRuleBll billRuleService = new BillRuleBll();
        private DataInterfaceBll dataInterfaceBll = new DataInterfaceBll();
        private UserBll userBll = new UserBll();
        private OrganizeBll organizeBll = new OrganizeBll();

        #region GET

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(int id)
        {
            var data = await CustomerbaseService.GetInfo(id);
            var output = data.MapTo<CustomerbaseUpOutput>();

            output.IsCreditI = false;

            string userId = UserProvider.Instance.Get().UserId;

            CustomeruserEntity customeruserEntity = await new CustomeruserBll().GetInfo(id, 1);

            if (customeruserEntity != null && customeruserEntity.Id > 0)
            {
                if (userId == customeruserEntity.UserId)
                {
                    //信贷用户是否是自己
                    output.IsCreditI = true;
                }
            }
            return Success(output);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList(CustomerbaseListQueryInput input)
        {
            var data = await CustomerbaseService.GetPageList(input);
            var outputList = data.list.MapToList<CustomerbaseListOutput>();
            outputList.ForEach(o =>
            {
                o.establishmentDate = o.establishmentDate != null ? string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(o.establishmentDate)) : null;
            });
            var output = new PageResult()
            {
                list = outputList,
                pagination = data.pagination
            };
            return Success(output);
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetListByUserId/{id}")]
        public async Task<ResponseResult> GetListByUserId(CustomerbaseListQueryInput input)
        {
            var data = await CustomerbaseService.GetPageListByuserId(input);
            var outputList = data.list.MapToList<CustomerbaseListOutput>();
            outputList.ForEach(o =>
            {
                o.establishmentDate = o.establishmentDate != null ? string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(o.establishmentDate)) : null;
            });
            var output = new PageResult()
            {
                list = outputList,
                pagination = data.pagination
            };
            return Success(output);
        }



        /// <summary>
        /// 获取列表   企业用户  ===  手机号码对应起来的 
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetBusPageList")]
        public async Task<ResponseResult> GetBusPageList(CustomerbaseListQueryInput input)
        {
            var data = await CustomerbaseService.GetBusPageList(input);
            var output = new PageResult()
            {
                list = data.list,
                pagination = data.pagination
            };
            return Success(output);
        }


        /// <summary>
        /// 获取列表   客户经理列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetCuseBusList")]
        public async Task<ResponseResult> GetCuseBusList(CustomerbaseListQueryInput input)
        {
            var data = await CustomerbaseService.GetCuseBusList(input);
            var output = new PageResult()
            {
                list = data.list,
                pagination = data.pagination
            };
            return Success(output);
        }


        /// <summary>
        /// 获取列表  信贷管家   列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetPagCuseList")]
        public async Task<ResponseResult> GetPagCuseList(CustomerbaseListQueryInput input)
        {
            var data = await CustomerbaseService.GetPagCuseList(input);
            var output = new PageResult()
            {
                list = data.list,
                pagination = data.pagination
            };
            return Success(output);
        }




        #endregion

        #region POST

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="input">新建输入</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] CustomerbaseCrInput input)
        {
            //判断下名字是否有重复的
            var data = await CustomerbaseService.GetInfo(input.customerName);
            if (data != null && !string.IsNullOrEmpty(data.CustomerName))
            {
                return Error("该企业已存在");
            }

            //判断下名字是否有重复的
            var data1 = await CustomerbaseService.GetInfoBySocialCreditCode(input.socialCreditCode);
            if (data1 != null && !string.IsNullOrEmpty(data1.CustomerName))
            {
                return Error("该信用代码企业已存在");
            }

            var entity = input.MapTo<CustomerbaseEntity>();
            await CustomerbaseService.Create(entity);
            return Success("新建成功");
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id">主键id</param>
        /// <param name="input">编辑输入</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(int id, [FromBody] CustomerbaseCrInput input)
        {
            CustomerbaseEntity customerbaseEntity = await CustomerbaseService.GetInfo(id);

            var entity = input.MapTo<CustomerbaseEntity>();
            var isOk = await CustomerbaseService.Update(id, entity);

            if (customerbaseEntity != null && entity != null && !string.IsNullOrEmpty(input.hideName) && customerbaseEntity.HideName != entity.HideName)
            {
                string str = $"欢迎{customerbaseEntity.CustomerName.Replace(entity.HideName, "***")}入驻九士企业";

                NewneedsEntity newneedsEntity = new NewneedsEntity();
                newneedsEntity.Id = Guid.NewGuid().ToString();
                newneedsEntity.Title = str;
                newneedsEntity.Description = str;
                newneedsEntity.UploadDate = DateTime.Now;
                newneedsEntity.EnabledMark = 1;
                newneedsEntity.UploadUser = "系统";
                //添加脱敏字段之后，添加首页信息
                await CustomerbaseService.newneedsEntityInsert(newneedsEntity);
            }

            return isOk > 0 ? Success("修改成功") : Error("修改失败");
        }


        /// <summary> 
        /// 审核
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpPost("Reviewer/{id}")]
        public async Task<ResponseResult> Reviewer(int id)
        {
            var entity = await CustomerbaseService.GetInfo(id);
            if (entity == null)
            {
                return Error("当前信息有误");
            }
            if (await userBll.IsExistByAccount(entity.MobilePhone, null))
            {
                return Error("账户手机号已存在，审核失败");
            }
            await CustomerbaseService.Reviewer(entity);
            return Success("审核成功");
        }

        /// <summary>
        /// 删除接口
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(int id)
        {
            var entity = await CustomerbaseService.GetInfo(id);
            var isOk = await CustomerbaseService.Delete(entity);
            return isOk > 0 ? Success("删除成功") : Error("删除失败");
        }

        #endregion

    }
}